#-*- coding:utf-8 -*-

from bottle import Bottle
from bottle import request
from bottle import HTTPError
from bottle import static_file

from entity import *
from dao import *
import os

from my_args import Args

app = Bottle()

#查找附近的停车位
@app.get('/park/gets')
def getParks():   
    args = Args(request.GET).require('long','lat')
    args.isFloat('long').isFloat('lat')
    if args.err:
        return args.err

    loc = [args.long,args.lat]
    parkDao = ParkDao()
    try:
        parks = parkDao.findParks(loc)
    finally:
        parkDao.close()

    result = getDictList(parks)
    return json_encode(result)

#增加停车位
#例如http://localhost:5551/park/gets?long=120&lat=30
@app.post('/park/add')
def addPark():

    args = Args(request.POST).require('name','long','lat','ownerId','spaceTotal')
    args.isFloat('long').isFloat('lat').isObjectId('ownerId').isInt('spaceTotal').isFloat('price')
    if args.err:
        return args.err

    #create park
    p = Park()
    p.name = args.name
    p.loc = [args.long,args.lat]
    p.ownerId = args.ownerId
    p.spaceTotal = args.spaceTotal
    p.spaceLeft = 0
    p.price = args.price

    pid = None
    parkDao = ParkDao()
    try:
        pid = parkDao.save(p)
    finally:
        parkDao.close()

    return pid

@app.post('/park/updPics')
def updParkPics():
    args = Args(request.POST).require('pid','pics')
    args.isObjectId('pid').isObjectIds('pics')
    if args.err:
        return args.err

    parkDao = ParkDao()
    try:
        park = parkDao.get(args.pid)
        park.pics = args.pics.split(',')
        parkDao.save(park)
    finally:
        parkDao.close()
    return args.pid

#增加车
@app.post('/car/add')
def addCar():
    args = Args(request.POST).require('uid')
    args.isObjectId('pid').isFloat('long').isFloat('lat')
    args.isObjectId('pic')
    if args.err:
        return args.err

    carDao = CarDao()
    car = Car()
    try:
        car.uid = args.uid
        car.pid = args.pid
        if args.long and args.lat:
            car.loc = [args.long, args.lat]
        car.pic = args.pic
        
        car.id = carDao.save(car)
    finally:
        carDao.close()

    return car.id

#获取某用户的所有车
@app.get('/car/getsByUser')
def getCarsByUid():
    args = Args(request.GET).require('uid')
    args.isObjectId('uid')
    if args.err:
        return args.err

    carDao = CarDao()
    cars = []
    try:
        cars = carDao.getCarsByUid(args.uid)
    except Exception, e:
        print e
    finally:
        carDao.close()

    result = getDictList(cars)
    return json_encode(result)


#上传停车场照片
#文档http://www.bottlepy.org/docs/dev/api.html#bottle.FileUpload
@app.post('/pic/upload')
def uploadPic():
    data = request.files.get('pic')
    if not data:
        return HTTPError(400,'亲，你确定你选择了图片吗?')
    pic = Pic()

    picDao = PicDao()

    try:
        pid = picDao.save(pic)

        #保存文件
        pic.fileName = '%s.%s' % (pid,data.filename)
        data.save(picDao.PicDir + pic.fileName, overwrite=False, chunk_size=65536)
        pic.pid = pid
        picDao.save(pic)
    finally:
        picDao.close()

    return pid

#查看图片
@app.get('/pic/view')
def viewPic():
    args = Args(request.GET).require('pid').isObjectId('pid')
    if args.err:
            return args.err

    pid = args.pid
    pic = None

    picDao = PicDao()
    try:
        pic = picDao.get(pid)
    finally:
        picDao.close()

    if pic and os.path.exists(picDao.PicDir + pic.fileName):
        return static_file(pic.fileName,root=picDao.PicDir)
    else:
        return HTTPError(404,'图片不存在哎!')

#增加用户(相当于注册)
@app.post('/user/add')
def addUser():

    args = Args(request.POST).require('name','mobile')
    if args.err:
        return args.err

    form = request.POST
    user = User()
    user.name = args.name
    user.mobile = args.mobile
    user.state = 0

    userDao = UserDao()
    try:
        user.uid = userDao.save(user)
    finally:
        userDao.close()

    return user.uid

#发表评论
@app.post('/comment/add')
def addComment():

    args = Args(request.POST).require('content','parkId','uid')
    args.isObjectId('uid').isObjectId('parkId')
    if args.err:
        return args.err

    comment = Comment()
    comment.content = args.content
    comment.parkId = args.parkId
    comment.uid = args.uid

    commentDao = CommentDao()
    try:
        commentDao.add(comment)
    finally:
        commentDao.close()
    
    #return的必须是字符串，所以不能直接返回cid
    return '%d' % comment.cid

#删除评论
@app.get('/comment/del')
def delComment():
    args = Args(request.GET).require('cid')
    args.isInt('cid')
    if args.err:
        return args.err

    cid = args.cid
    commentDao = CommentDao()
    try:
        commentDao.delete(cid)
    finally:
        commentDao.close()

    #return的必须是字符串，所以不能直接返回cid
    return '%d' % cid



